/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlets;

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.akcess.vo.*; //Para usar la clase Usuarios.
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author Ramon
 */
public class loginFiltro implements Filter {

    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;

    public loginFiltro() {
    } 

    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
	throws IOException, ServletException {
	if (debug) log("loginFiltro:DoBeforeProcessing");
	//
	// Write code here to process the request and/or response before
	// the rest of the filter chain is invoked.
	//

            
	
    } 

    private void doAfterProcessing(ServletRequest request, ServletResponse response)
	throws IOException, ServletException {
	if (debug) log("loginFiltro:DoAfterProcessing");
	//
	// Write code here to process the request and/or response after
	// the rest of the filter chain is invoked.
	//
	
	

	
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {

	    if (debug) log("loginFiltro:doFilter()");

	//doBeforeProcessing(request, response);
	Throwable problem = null;

	try {
            HttpSession session = ((HttpServletRequest)request).getSession(true);
            HttpServletRequest req=(HttpServletRequest)request;
            String camino=req.getRequestURI();//Ahi esta el lugar a donde se quiere ir...
            String accion = req.getQueryString();//La operacion que quiere hacer..
            
            if(accion !=null)
                accion=accion.substring(6);
           String tieneSesion=(String)session.getAttribute("estaDentro");
           
           //Empiezo a filtrar por los permisos que tiene el usuario.
           
           if( camino!=null && camino.compareTo("/GestionarSolicitudes_de_Registro")==0 ){
               if(accion.compareTo("crear")==0)
               {
                   
                   chain.doFilter(request, response);
               }
                    
             
           }
           if(camino.compareTo("/SessionLogin")==0){//Le dejo pasar para que se pueda loggear.
               chain.doFilter(request, response);
           }else if(tieneSesion== null || tieneSesion.compareTo("true")!=0)
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/login.jsp");
                dispatcher.forward(request, response);
            }
            else if(tieneSesion!= null || tieneSesion.compareTo("true")==0)
            {
                Usuarios user= (Usuarios)session.getAttribute("datosUser");
                if(accion==null && camino.compareTo("/")==0)
                    chain.doFilter(request, response);
                else if(this.tienePermiso(user, camino, accion))
                    chain.doFilter(request, response);
                else{
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/errores/SinPermiso.jsp");
                    dispatcher.forward(request, response);
                }
                    
            }
               
            
	   
	}
	catch(Throwable t) {
	    //
	    // If an exception is thrown somewhere down the filter chain,
	    // we still want to execute our after processing, and then
	    // rethrow the problem after that.
	    //
	    problem = t;
	    t.printStackTrace();
	}

	//doAfterProcessing(request, response);

	//
	// If there was a problem, we want to rethrow it if it is
	// a known type, otherwise log it.
	//
	if (problem != null) {
	    if (problem instanceof ServletException) throw (ServletException)problem;
	    if (problem instanceof IOException) throw (IOException)problem;
	    sendProcessingError(problem, response);
	}
    }

    
    public boolean tienePermiso(Usuarios user, String camino, String consulta){
        NombresModulosOperaciones[] permisos=user.getPermisos();
        
        String modulo=camino.substring(10);
        modulo=modulo.replace("_", " ");
        consulta=consulta.replace("_", " ");
        for (int i = 0; i < permisos.length; i++) {
            if(modulo.compareTo(permisos[i].getNombreModulo())==0)
            {
                if(consulta.compareTo(permisos[i].getNombrePermiso())==0)
                {
                    return true;
                }else if(consulta.contains("opModificar"))
                {
                    return true;
                }else if(consulta.contains("opAgregar"))
                {
                    return true;
                }else if (consulta.contains("Ver"))
                {
                    return true;
                }else if(consulta.contains("opBorrar"))
                {
                    return true;
                }else if(consulta.contains("opCambiar")) {
                    return true;
                }else if(consulta.contains("modificarRol")) {
                    return true;
                }else if(consulta.contains("modificacion")) {
                    return true;
                }else if(consulta.contains("agregacion")) {
                    return true;
                }else if(consulta.contains("opAprobar")) {
                    return true;
                }else if(consulta.contains("opRechazar")) {
                    return true;
                }else if(consulta.contains("crear")) {
                    return true;
                }else if(consulta.contains("opAgregarAtributo")) {
                    return true;
                }else if(consulta.contains("traerCampos")) {
                    return true;
                }else if(consulta.contains("opAsignar")) {
                    return true;
                }else if(consulta.contains("opReset")) {
                    return true;
                }else if(consulta.contains("ListarReservas")) {
                    return true;
                }else if(consulta.contains("listarAJAX")) {
                    return true;
                }else if(consulta.contains("ModificarReservas")) {
                    return true;
                }else if(consulta.contains("CancelarReservas")) {
                    return true;
                }else if(consulta.contains("opCancelar")) {
                    return true;
                }else if(consulta.contains("ListarSolicitudes")) {
                    return true;
                }else if(consulta.contains("AprobarSolicitudes")) {
                    return true;
                }else if(consulta.contains("RechazarSolicitudes")) {
                    return true;
                }else if(consulta.contains("AnularSolicitudes")) {
                    return true;
                }else if(consulta.contains("consultarNameOp")) { 	                    
                    return true;
                }else if(consulta.contains("traerSolicitante")) {
                    return true; 
                }else if(consulta.contains("ListarRegistrar")) {
                    return true; 
                }else if(consulta.contains("opRegistrar")) {
                    return true; 
                }else if(consulta.contains("aprobado")) {
                    return true; 
                }else if(consulta.contains("ListarMis")) {
                    return true; 
                }else if(consulta.contains("CancelarMis")) {
                    return true; 
                }
                
            }
            
        }
        return false;
        
    }
    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
	return (this.filterConfig);
    }


    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {

	this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     *
     */
    public void destroy() { 
    }


    /**
     * Init method for this filter 
     *
     */
    public void init(FilterConfig filterConfig) { 

	this.filterConfig = filterConfig;
	if (filterConfig != null) {
	    if (debug) { 
		log("loginFiltro:Initializing filter");
	    }
	}
    }

    /**
     * Return a String representation of this object.
     */
    public String toString() {

	if (filterConfig == null) return ("loginFiltro()");
	StringBuffer sb = new StringBuffer("loginFiltro(");
	sb.append(filterConfig);
	sb.append(")");
	return (sb.toString());

    }



    private void sendProcessingError(Throwable t, ServletResponse response) {
	
	String stackTrace = getStackTrace(t); 

	if(stackTrace != null && !stackTrace.equals("")) {

	    try {
		    
		response.setContentType("text/html");
		PrintStream ps = new PrintStream(response.getOutputStream());
		PrintWriter pw = new PrintWriter(ps); 
		pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
		    
		// PENDING! Localize this for next official release
		pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); 
		pw.print(stackTrace); 
		pw.print("</pre></body>\n</html>"); //NOI18N
		pw.close();
		ps.close();
		response.getOutputStream().close();;
	    }
		
	    catch(Exception ex){ }
	}
	else {
	    try {
		PrintStream ps = new PrintStream(response.getOutputStream());
		t.printStackTrace(ps);
		ps.close();
		response.getOutputStream().close();;
	    }
	    catch(Exception ex){ }
	}
    }

    public static String getStackTrace(Throwable t) {

	String stackTrace = null;
	    
	try {
	    StringWriter sw = new StringWriter();
	    PrintWriter pw = new PrintWriter(sw);
	    t.printStackTrace(pw);
	    pw.close();
	    sw.close();
	    stackTrace = sw.getBuffer().toString();
	}
	catch(Exception ex) {}
	return stackTrace;
    }

    public void log(String msg) {
	filterConfig.getServletContext().log(msg); 
    }

    private static final boolean debug = false;
}
